package com.woniuxy.classteacher.service.impl;

import com.woniuxy.classteacher.mapper.*;
import com.woniuxy.classteacher.mqsend.EmailPhone;
import com.woniuxy.classteacher.service.ClassTeacherService;
import com.woniuxy.classteacher.uitility.ChineseExcel;
import com.woniuxy.classteacher.uitility.ScoreExcelSend;
import com.woniuxy.classteacher.uitility.StudentInfoExcelSend;
import com.woniuxy.commons.entity.*;
import com.woniuxy.commons.entity.wyh.GradeInfo;
import com.woniuxy.commons.entity.wyh.TeacherInfo;
import com.woniuxy.commons.entity.wyh.TeamInfo;
import com.woniuxy.commons.exception.*;
import com.woniuxy.commons.service.RemotePaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author 李英勇、牟强
 * @date 2020/7/16 - 16:14
 */
@Service
public class ClassTeacherServiceImpl implements ClassTeacherService {
    @Autowired
    private ClassTeacherMapper classTeacherMapper;
    @Autowired
    private ChangeClassMapper changeClassMapper;
    @Autowired
    private EmailPhone emailPhone;//生产者
    @Autowired
    private StudentInfoMapper studentInfoMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private KnowledgeDotMapper knowledgeDotMapper;
    @Autowired
    private RemotePaperService remotePaperService;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GradeMapper gradeMapper;

    @Override
    public List<StudentInfo> all() {
        return classTeacherMapper.all();
    }

    @Override
    public List<Vedio> findVedioByTeacherid(int teacherid, int page, int limit) {
        return classTeacherMapper.findVedioByTeacherid(teacherid, page, limit);
    }

    @Override
    public long findVideoCountByTeacherid(int teacherid) {
        return classTeacherMapper.findVideoCountByTeacherid(teacherid);
    }

    /**
     * @Author: 李英勇
     * @Description: 通过refreshToken查出班主任管的所有班级和学生
     * @DateTime: 2020/7/28 15:02
     * @Params: [refreshToken]
     * @Return java.util.Map<java.lang.String, java.util.List < com.woniuxy.commons.entity.StudentInfo>>
     */
    @Override
    @Transactional
    public Map<String, List<StudentInfo>> findStudentByTmid(String refreshToken) {
        //准备map封装数据
        Map<String, List<StudentInfo>> map = new HashMap<>();
        //在redis中获取用户的role和rid
        //通过refreshToken获取数据
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshToken);
        //获取role
        String role = (String) data.get("role");
        //获取rid
        int rid = (int) data.get("rid");
        if ("teacher".equals(role)) {
            //通过rid查询班主任id
            List<Integer> tmids = changeClassMapper.findTmIdByTeacherId(rid);
            if (tmids.size() != 0) {
                //通过tmids查询所管的所有班级
                List<TeamInfo> teamInfos = classMapper.findTeamInfoByTmId(tmids);
                //遍历班级分别查出每个班的学生
                for (int i = 0; i < teamInfos.size(); i++) {
                    Integer teId = teamInfos.get(i).getTeId();
                    List<StudentInfo> stus = studentMapper.findStusByClassid(teId);
                    map.put(teamInfos.get(i).getTname(), stus);
                }
            }
        }
        return map;
    }

    /**
     * @Author: 李英勇
     * @Description: 通过tcid获取老师的信息
     * @DateTime: 2020/7/28 17:29
     * @Params: [tcid]
     * @Return com.woniuxy.commons.entity.wyh.TeacherInfo
     */
    @Override
    public TeacherInfo findTeacherByTcid(int tcid) {
        TeacherInfo teacherInfo = classTeacherMapper.findTeacherInfoByTcid(tcid);
        return teacherInfo;
    }

    @Override
    public List<TeamInfo> findClazz(String refreshToken) {
        List<TeamInfo> list = new ArrayList<>();
        //通过refreshToken获取数据
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshToken);
        //获取role
        String role = (String) data.get("role");
        //获取rid
        int rid = (int) data.get("rid");
        if ("teacher".equals(role)) {
            //通过rid查询班主任id
            List<Integer> tmids = changeClassMapper.findTmIdByTeacherId(rid);
            if (tmids.size() != 0) {
                //通过tmids查询所管的所有班级
                List<TeamInfo> teamInfos = classMapper.findTeamInfoByTmId(tmids);
                for (int i = 0; i < teamInfos.size(); i++) {
                    String tname = teamInfos.get(i).getTname();
                    //通过班级查询年级
                    GradeInfo gradeInfo = gradeMapper.findGradeByGaid(teamInfos.get(i).getGaId());
                    //设置年级信息
                    teamInfos.get(i).setGradeInfo(gradeInfo);
                    list.add(teamInfos.get(i));

                }
            }
        }
        return list;
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/30/030 15:06
     * @Description: 批量从excel录入学生信息
     * @Param: [file, request, classid]
     * @return: void
     */
    @Transactional
    @Override
    public void StudentInfoEnteringService(MultipartFile file, HttpServletRequest request, int classid) {
        //从request获取refreshtoken
        String refreshtoken = request.getHeader("refreshToken");
        //从redis获取教师Id
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshtoken);
        Integer rid = (Integer) data.get("rid");
        //查询出教师的学校Id
        Integer schoolId = teacherMapper.findTeacherSchoolIdByTeacherId(rid);
        //创建处理excel的类
        StudentInfoExcelSend excelSend = new StudentInfoExcelSend();
        //解析excel，获取上传的事件单
        List<StudentInfo> studentInfos = excelSend.getExcelInfo(file);
        //循环设置
        for (StudentInfo s : studentInfos) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyss");
            String format = sdf.format(new Date());
            int num = (int) (Math.random() * 10);
            String account = format + num;
            //设置账户
            s.setAccount(format + num);
            //设置密码
            s.setPwd("000000");
            // 设置班级id 从前端下拉框获取
            s.setClassid(classid);
            // 设置学校
            s.setSchoolid(schoolId);
            //默认不是差生
            s.setBadstudent(0);
        }
        //添加到数据库并返回id主键
        classTeacherMapper.batchAddStudentInfo(studentInfos);
        //将学生账号密码,手机号和主键id传入user表
        userMapper.batchAddStudenInfoArriveUser(studentInfos);
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/18/018 11:12
     * @Description: 修改学生密码
     * @Param: [stuid]
     * @return: void
     */
    @Override
    public void updateStudentPwd(int stuid) {
        //先查再改
        StudentInfo student = classTeacherMapper.findStudentBySid(stuid);
        if (student == null) {
            throw new StudentNotExistException("需要修改的学生不存在");
        }
        //重置学生密码
        classTeacherMapper.updateStudentPwd(stuid, "000000");
        //异步发送邮件和手机短信
        emailPhone.send(student);
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/20/020 11:07
     * @Description: 学生转班
     * @Param: [stuid, classid]
     * @return: void
     */
    @Transactional
    @Override
    public void changeClass(ChangeClass changeClass, HttpServletRequest request) {
        //从request中获取refreshtoken
        String refreshtoken = request.getHeader("refreshToken");
        //通过token获取教师id
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshtoken);
        //获取教师id
        int rid = (Integer) data.get("rid");
        // 判断学生是否在其他转班过程中，在转班过程中未结束不能转班
        Integer n = changeClassMapper.isStudentInChangeClassPeriod(changeClass.getStudentId());
        if (n > 0) {
            throw new StudentInChangeClassException("该学生还有转班申请未处理");
        }
        //判断该学生是否已经在该班级
        Integer num = studentInfoMapper.computeStudentAndClassNum(changeClass.getStudentId(), changeClass.getAwaitClassId());
        if (num > 0) {
            throw new StudentExistAwaitClassException("学生已存在待转入班级");
        }
        //设置转班数据
        //班主任教师id 被转班的班主任 根据班级查询班主任再查询到老师id
        Integer teacherId = classMapper.findClassTeacherIdByClassId(changeClass.getAwaitClassId());
        changeClass.setTeacherId(teacherId);
        //通过学生id获得学生姓名
        String sname = studentInfoMapper.findStudentNameBySId(changeClass.getStudentId());
        //通过班级id获得班级名称
        String cname = classMapper.findClassNameByCId(changeClass.getAwaitClassId());
        //通过学生id查询原来班级的名称
        String originClassName = classMapper.findClassNameByStudentId(changeClass.getStudentId());
        //如果被转入班级和原班级名称相同则不能转班
        if (originClassName.equals(cname)) {
            throw new CannotChangeClassException("原班与待转入班相同，不能转班");
        }
        changeClass.setOriginClassName(originClassName);
        changeClass.setStudentName(sname);
        changeClass.setAwaitClassName(cname);
        changeClass.setStatus(ChangeClass.AWAIT);//等待转入
        changeClass.setLaunchTeacherId(rid);//原班主任Id
        changeClassMapper.add(changeClass);
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/20/020 12:16
     * @Description: 转班列表
     * @Param: [teacherId]
     * @return: java.util.List<com.woniuxy.commons.entity.ChangeClass>
     */
    @Override
    public List<ChangeClass> changeClassList(HttpServletRequest request) {
        //从request中获取refreshtoken
        String refreshtoken = request.getHeader("refreshToken");
        //通过token获取教师id
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshtoken);
        //获取教师id
        int rid = (Integer) data.get("rid");
        //获取转班列表
        List<ChangeClass> changeClassList = changeClassMapper.findChangeClassByTeacherId(rid);
        return changeClassList;
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/21/021 11:40
     * @Description: 拒绝学生转班
     * @Param: [cId]
     * @return: void
     */
    @Override
    public void refuseStudentChangeClass(int cId) {
        changeClassMapper.updateChangeClassStatus(ChangeClass.REFUSE, cId);
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/21/021 14:53
     * @Description: 同意学生转班
     * @Param: [changeClass]
     * @return: void
     */
    @Override
    public void consentStudentChangeClass(ChangeClass changeClass) {
        //先修改转班表状态
        int cId = changeClass.getCId();
        System.out.println("转班表id" + cId);
        changeClassMapper.updateChangeClassStatus(ChangeClass.END, cId);//已完成
        //修改学生表班级外键
        int awaitClassId = changeClass.getAwaitClassId();
        System.out.println("班级Id" + awaitClassId);
        int studentId = changeClass.getStudentId();
        System.out.println("学生id" + studentId);
        studentInfoMapper.updateStudentClassIdBySutdentId(studentId, awaitClassId);
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/21/021 16:29
     * @Description: 录入学生高考分数
     * @Param: [file]
     * @return: void
     */
    @Override
    public void addCollegeEntranceScore(MultipartFile file, HttpServletRequest request, int classid) {
        //从request中获取refreshtoken
        String refreshtoken = request.getHeader("refreshToken");
        //通过token获取教师id
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshtoken);
        //获取教师id
        int rid = (Integer) data.get("rid");
        //查询出教师的学校Id
        Integer schoolId = teacherMapper.findTeacherSchoolIdByTeacherId(rid);
        //创建处理excel的类
        ScoreExcelSend excelSend = new ScoreExcelSend();
        //解析excel，获取上传的事件单
        List<CollegeEntranceScore> collegeEntranceScores = excelSend.getExcelInfo(file);
        //设置学校id和所在班级id
        for (CollegeEntranceScore c : collegeEntranceScores) {
            c.setSchoolid(schoolId);
            c.setClassid(classid);
        }
        studentInfoMapper.batchAddCollegeEntranceScore(collegeEntranceScores);
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/23/023 11:12
     * @Description: 初始化添加学生信息时的班级下拉框
     * @Param: []
     * @return: java.util.List<com.woniuxy.commons.entity.wyh.TeamInfo>
     */
    @Override
    public List<TeamInfo> initEnteringStudentInfoClass(HttpServletRequest request) {
        //从request中获取refreshtoken
        String refreshtoken = request.getHeader("refreshToken");
        //通过token获取教师id
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshtoken);
        //获取教师id
        int rid = (Integer) data.get("rid");
        //先查询出当前登录教师的班主任id
        List<Integer> tmIds = changeClassMapper.findTmIdByTeacherId(rid);
        //判断是否是班主任
        if (tmIds.size() < 1) {
            throw new NotClassMasterException("不是班主任，无法录入学生信息");
        }
        //通过班主任id批量查询班级信息
        List<TeamInfo> teamInfos = classMapper.findTeamInfoByTmId(tmIds);

        return teamInfos;
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/23/023 14:49
     * @Description: 教师上传试卷
     * @Param: [file, refreshToken, paperType]
     * @return: void
     */
    @Override
    public void uploadingTestPapera(MultipartFile file, String refreshToken, int paperType, String grade) {
        TestPaper testPaper = null;
        System.out.println(refreshToken);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(refreshToken);
        //从数据库中获取出题人id
        Integer rid = (Integer) entries.get("rid");
        System.out.println("教师id为" + rid);
        //通过id获得出题人姓名
        String teacherName = teacherMapper.findTeacherNameByTeacherId(rid);
        System.out.println(teacherName);
        Long g = Long.valueOf(grade);
        //判断上传的科目
        //选择语文试卷模版,传入mapper查询知识点数据库
        ChineseExcel chineseExcel = new ChineseExcel(knowledgeDotMapper);
        testPaper = chineseExcel.getExcelInfo(file, teacherName, g);
        System.out.println(testPaper);
        //调用试卷上传模块上传试卷
        remotePaperService.insertPaper(testPaper);
        //设置作业类型 1,当天作业;2,周末作业;3,寒暑假作业;4,月考;5,期中考;6,期末考;
        System.out.println(testPaper);
        testPaper.setPaperType(paperType);
    }

    /**
     * @Author: 牟强
     * @Date: 2020/7/28/028 17:51
     * @Description: 初始化学生转班的所有班级
     * @Param: [request]
     * @return: java.util.List<com.woniuxy.commons.entity.wyh.TeamInfo>
     */
    @Override
    public List<TeamInfo> iniChangeClass(HttpServletRequest request) {
        //从request中获取refreshtoken
        String refreshtoken = request.getHeader("refreshToken");
        //通过token获取教师id
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshtoken);
        //获取教师id
        int rid = (Integer) data.get("rid");
        //查询出教师的学校Id
        Integer schoolId = teacherMapper.findTeacherSchoolIdByTeacherId(rid);
        //通过学校Id找出所有该学校的年级
        List<Integer> gradeIds = classMapper.findGradIdBySchoolId(schoolId);
        //通过年级id批量查找班级
        List<TeamInfo> teamInfos = classMapper.findTeamInfoByGradeIds(gradeIds);
        return teamInfos;
    }

}
